package com.xnj.testweb.common.utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Base64;

public class AESUtils {
    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";
    // 密钥仍然固定（生产环境应从安全存储获取）
    private static final SecretKey KEY;

    static {
        try {
            // 生成固定密钥（仅示例）
            KEY = new SecretKeySpec(
                    Base64.getDecoder().decode("K7gNU3sdo+OL0wNhqoVWhr3g6s1xYv72ol/pe/Unols="),
                    ALGORITHM
            );
        } catch (Exception e) {
            throw new RuntimeException("初始化加密失败", e);
        }
    }

    // 加密方法（动态生成IV）
    public static String encrypt(String input) throws Exception {
        // 每次加密生成随机IV
        byte[] ivBytes = new byte[16];
        new SecureRandom().nextBytes(ivBytes);
        IvParameterSpec iv = new IvParameterSpec(ivBytes);

        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, KEY, iv);
        byte[] encryptedBytes = cipher.doFinal(input.getBytes());

        // 返回 "IV + 密文" 的Base64组合（IV不需要保密，但必须唯一）
        byte[] combined = new byte[ivBytes.length + encryptedBytes.length];
        System.arraycopy(ivBytes, 0, combined, 0, ivBytes.length);
        System.arraycopy(encryptedBytes, 0, combined, ivBytes.length, encryptedBytes.length);

        return Base64.getEncoder().encodeToString(combined);
    }

    // 解密方法
    public static String decrypt(String encryptedInput) throws Exception {
        byte[] combined = Base64.getDecoder().decode(encryptedInput);

        // 提取IV（前16字节）
        byte[] ivBytes = new byte[16];
        System.arraycopy(combined, 0, ivBytes, 0, 16);
        IvParameterSpec iv = new IvParameterSpec(ivBytes);

        // 提取密文（剩余部分）
        byte[] encryptedBytes = new byte[combined.length - 16];
        System.arraycopy(combined, 16, encryptedBytes, 0, encryptedBytes.length);

        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, KEY, iv);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

        return new String(decryptedBytes);
    }
}